package com.yohann.eduservice.listener;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yohann.eduservice.entity.EduSubject;
import com.yohann.eduservice.entity.excel.SubjectData;
import com.yohann.eduservice.service.EduSubjectService;
import com.yohann.servicebase.exception.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * <p>
 * Excel监听器
 * </p>
 *
 * @author Yohann
 * @since 2020/8/7
 */
@Component
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
    @Autowired
    private EduSubjectService subjectService;

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData == null){
            throw new GuliException(20001,"文件为空");
        }

        EduSubject existOneSubject = this.existOneSubject(subjectService, subjectData.getOneName());
        if (existOneSubject == null){
            EduSubject subject = new EduSubject();
            subject.setParentId("0");
            subject.setTitle(subjectData.getOneName());

            subjectService.save(subject);
        }else {
            String pid = existOneSubject.getId();
            EduSubject existTwoSubject = this.existTwoSubject(subjectService, subjectData.getTwoName(), pid);
            if (existTwoSubject == null){
                EduSubject subject = new EduSubject();
                subject.setParentId(pid);
                subject.setTitle(subjectData.getTwoName());

                subjectService.save(subject);
            }
        }
    }

    /**
     * 判断一级分类是否重复
     * @param subjectService
     * @param name
     * @return
     */
    private EduSubject existOneSubject(EduSubjectService subjectService, String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id", "0");

        return subjectService.getOne(wrapper);
    }

    /**
     * 判断二级分类是否重复
     * @param subjectService
     * @param name
     * @param pid
     * @return
     */
    private EduSubject existTwoSubject(EduSubjectService subjectService, String name, String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id", pid);

        return subjectService.getOne(wrapper);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}